package com.whf.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/7/18 0018.
 */
public class CookieUtil {
    //设置
    public static void set(HttpServletResponse response,
                           String key,
                           String value,
                           int maxAge) {

        Cookie cookie=new Cookie(key,value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
    //获取
    public static Cookie get(HttpServletRequest request,
                           String name){
        Cookie[] cookies = request.getCookies();
        Map<String, Cookie> cookieMap = array2Map(cookies);
        if(cookieMap==null){
            return null;
        }
        if(cookieMap.containsKey(name)){
            return cookieMap.get(name);
        }else{
            return null;
        }


    }
    //cookie数组转换为map
    private static Map<String,Cookie> array2Map(Cookie[] cookies){
        if(cookies.length==0){
            return null;
        }
        Map<String,Cookie> map=new HashMap<>();
        for(Cookie cookie:cookies){
            map.put(cookie.getName(),cookie);
        }
        return map;
    }
}
